package com.taotao.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.EasyUIResult;
import com.taotao.common.IDUtils;
import com.taotao.common.TaotaoResult;
import com.taotao.mapper.TbItemDescMapper;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemExample;
import com.taotao.pojo.TbItemExample.Criteria;
import com.taotao.service.ItemParamItemService;
import com.taotao.service.ItemService;

@Service
public class ItemServiceImpl implements ItemService{
	@Autowired
	private TbItemMapper itemMappper;
	@Autowired
	private TbItemDescMapper itemDescMapper;
	@Autowired
	private ItemParamItemService itemParamService;
	
	@Override
	public TbItem selectItem(Long id) {
		TbItemExample item=new TbItemExample();
		Criteria createCriteria = item.createCriteria();
		createCriteria.andIdEqualTo(id);
		List<TbItem> selectByExample = itemMappper.selectByExample(item);
		return selectByExample.get(0);
	}
	@Override
	public EasyUIResult getItemList(Integer page, Integer rows) {
		TbItemExample item=new TbItemExample();
		PageHelper.startPage(page, rows);
		List<TbItem> TbItems = itemMappper.selectByExample(item);
		PageInfo<TbItem> pageInfo=new PageInfo<>(TbItems);
		long total = pageInfo.getTotal();
		EasyUIResult result=new EasyUIResult();
		result.setRows(TbItems);
		result.setTotal(total);
		return result;
	}
	@Override
	public TaotaoResult saveItem(TbItem tbItem,TbItemDesc itemDesc,String itemParam) {
		try {
			Long id=IDUtils.genItemId();
			tbItem.setId(id);
			tbItem.setStatus((byte) 1);
			Date date=new Date();
			tbItem.setCreated(date);
			tbItem.setUpdated(date);
			itemMappper.insert(tbItem);
			//保存商品描述
			itemDesc.setItemId(id);
			itemDesc.setCreated(date);
			itemDesc.setUpdated(date);
			itemDescMapper.insert(itemDesc);
			//保存商品规格参数
			TaotaoResult result=itemParamService.saveItemParamItem(itemParam, id);
			if(result.getStatus()!=200){
				throw new Exception();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, "保存失败!"); 
		}
		
		return TaotaoResult.ok();
	}

	
}
